﻿#ifndef _TIANYU_SERVER_BASE_
#define _TIANYU_SERVER_BASE_

#include <stdint.h>
#include <string>
#include "../share/code_def.h"
#include "../share/proxy_head.h"
#include "../../3rd/st_asio_wrapper/service_pump.h"
#include "client_msg.h"
#include "server_msg.h"
#include "SyncQueue.h"
#include "proxy_msg_mgr.h"
using namespace st_asio_wrapper;

#ifdef _MSC_VER
void SetCtrlCHandle(bool bAdd);
#endif

enum EServiceStatus
{
	SERVICE_INIT = 1,
	SERVICE_ISRUNNING = 2,
	SERVICE_WAITTING_EXIT = 3,
	SERVICE_FINAL = 4,
	SERVICE_EXIT = 5,
};

class IService
{
public:
	IService();
	virtual ~IService() {};
public:
	virtual int32_t Initialize() = 0;
	virtual int32_t ServerStart() { return 0; }
	virtual int32_t Finalize() = 0;
	virtual EServiceType GetServiceType() = 0;
	uint32_t GetServiceID() const { return service_id_; }
	EServiceStatus GetServiceStatus() const;
	EServiceStatus SetServiceStatus(EServiceStatus service_status);

	int32_t ServiceMain(int32_t argc, char** argv);
	int32_t ServiceLogic();
	virtual void TickUpdate() {};
	int32_t Exit(int32_t exit_code);

	virtual int32_t ServiceMainLoop() { return 0; }

	/**
	* @brief 收到信号SIGUSR2
	*/
	virtual void OnUserSignal2();
	/**
	* @brief 收到信号SIGURS1
	*/
	virtual void OnUserSignal1();
public:
	virtual int32_t AddClientMsg(uint32_t socketId, uint32_t msgId, std::string &msg);
	virtual int32_t AddServerMsg(uint32_t msgId, std::string &msg, const common::CProxyHead& head);
	// 从网络层往业务层抛出断开连接事件
	virtual void del_client_socket(uint32_t fd){}
	// 主动断开连接，去往下调用断开连接事件
	virtual void client_close_socket(uint32_t fd){}
	service_pump& get_service_pump() { return pump_; }

	const std::string& GetLogDir() { return service_log_dir_; }

	virtual void ProcessClientMsg(CClientSocketMsg& val) {};
	virtual void ProcessServerMsg(CProxySocketMsg& val);
	CProxyMsgFactory& GetProxyMsgFactory() { return proxy_msg_mgr_; }
protected:
	void AddClientMsgPtr(CClientSocketMsg& val);
	void AddServerMsgPtr(CProxySocketMsg& val);
	void processSocketMessage();
	void processServerSocketMessage();
protected:
	int32_t exit_code_;/**<退出码  */
	EServiceStatus service_status_;
	uint32_t service_id_;
	service_pump pump_;

	int64_t tick_time_;
	std::string service_log_dir_;
	int32_t max_client_count_;
protected:
	SyncQueue<CClientSocketMsg>		m_queue_socket;
	SyncQueue<CProxySocketMsg>		m_queue_server_socket;
	CProxyMsgFactory proxy_msg_mgr_;
};

#endif